package com.haiheng.library_base.http

import android.content.Context
import android.text.TextUtils
import android.util.Log
import com.haiheng.library.log.LogUtils
import okhttp3.*
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import okhttp3.logging.HttpLoggingInterceptor
import java.io.File
import java.io.IOException
import java.util.concurrent.TimeUnit

/**
 *
 * @Des:
 * @Author: hwz
 * @Date:2022/4/15 0015
 * @Version: 1.0
 */
object OkHelper {
    private var httpClient: OkHttpClient? = null

    @JvmStatic
    @Synchronized
    fun httpClient(context: Context,retrofitParams: RetrofitParams): OkHttpClient = httpClient ?: OkHttpClient().newBuilder()
        .readTimeout(15000L, TimeUnit.MILLISECONDS)
        .writeTimeout(15000L, TimeUnit.MILLISECONDS)
        .connectTimeout(15000L, TimeUnit.MILLISECONDS)
//        .cookieJar(CookieJar())
        .cache(Cache(File(context.cacheDir, "okhttp"), 250L * 1024 * 1024))
        .addInterceptor(BaseUrlInterceptor(retrofitParams.getBaseUrlAdapter()?.getAppendBaseUrl()))
        .addNetworkInterceptor(
            HttpLoggingInterceptor(HttpLoggingInterceptor.Logger {
                //访问网络请求，和服务端响应请求时。将数据拦截并输出
                LogUtils.d("okhelp RetrofitHelper-Http: $it")
            }).setLevel(HttpLoggingInterceptor.Level.BODY)
        )
        .build()

    /**
     * baseurl拦截器,支持多个baseurl
     */
    private class BaseUrlInterceptor(private val baseUrlMap: Map<String, String>?) :
        Interceptor {
        @Throws(IOException::class)
        override fun intercept(chain: Interceptor.Chain): Response {
            //获取request
            val request: Request = chain.request()
            //获取request的创建者builder
            val builder: Request.Builder = request.newBuilder()
            //从request中获取headers，通过给定的键url_name
            val headerValues = request.headers(Domain.KEY_NAME)
            if (headerValues != null
                && headerValues.size > 0
                && baseUrlMap != null
                && baseUrlMap.size > 0
            ) {
                //匹配获得新的BaseUrl
                var newBaseUrl: HttpUrl? = null
                val headerValue = headerValues[0]
                val baseUrl = baseUrlMap[headerValue]
                if (!TextUtils.isEmpty(baseUrl)) {
                    //如果有这个header，先将配置的header删除，因此header仅用作app和okhttp之间使用
                    builder.removeHeader(Domain.KEY_NAME)
                    newBaseUrl = baseUrl!!.toHttpUrlOrNull()
                } else {
                    return chain.proceed(request)
                }

                //从request中获取原有的HttpUrl实例oldHttpUrl
                val oldHttpUrl = request.url
                //重建新的HttpUrl，修改需要修改的url部分
                val newFullUrl = oldHttpUrl
                    .newBuilder()
                    .scheme(newBaseUrl!!.scheme)
                    .host(newBaseUrl.host)
                    .port(newBaseUrl.port)
                    .build()
                //重建这个request，通过builder.url(newFullUrl).build()；
                //然后返回一个response至此结束修改
                return chain.proceed(builder.url(newFullUrl).build())
            }
            return chain.proceed(request)
        }
    }

}